<?php

namespace EasyVote\EasyVoteBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use EasyVote\EasyVoteBundle\Entity\Degree;
use EasyVote\EasyVoteBundle\Form\EntityStorage;
use EasyVote\EasyVoteBundle\Entity\User;
use EasyVote\EasyVoteBundle\Entity\Role;
use EasyVote\EasyVoteBundle\Entity\Election;
use Symfony\Component\HttpFoundation\Request;

class AdminController extends Controller
{
    /**
     * @Template
     * This shows the a form that can move a user from an admin role to
     * a normal role, or a normal role to an admin role.
     * @param Request $request
     * @return Response The form to add and remove admins and redirect to the page
     *         if the form has already been submitted
     */
    public function showAction(Request $request)
    {
		// Get the role and user repositories
        $em = $this->getDoctrine()->getManager();
		$roleRepo = $em->getRepository('EasyVoteBundle:Role');  
		$userRepo = $em->getRepository('EasyVoteBundle:User');
		
		// If the user is not an admin, they'll get redirected back to the
		// elections list page
		/*
		if ($this->getUser()->isAdmin() == false) {
           if ($request->headers->get('referer'))
                return $this->redirect($request->headers->get('referer'));
            else
                return $this->redirect($this->generateUrl('elections_show'));
		}
		*/
		// Go through all the users in the repository
		$adminArray = array();
		$userArray = array();
		foreach ($userRepo->findAll() as $user)
		{
			// If the user is an an admin, put the user in the adminArray
			if ($user->isAdmin())
			{
				array_push($adminArray, $user);				
			}
			// Everyone else goes in the userArray
			else 
			{
				array_push($userArray, $user);								
			}
		}

		// The form that will be generated on the page
		$form = $this->createFormBuilder()
			// Allows you to select a user euid to add as an admin
		    ->add('addEuidAsAdmin', 'entity', array(
					'class' => 'EasyVoteBundle:User', 
					'property' => 'euid',
					'choices' => $userArray,
					'empty_value' => 'Choose an option', 
					'required' => false,
					'multiple' => false
				)
			)
			// Allows you to select a user euid to remove as an admin
		    ->add('removeEuidAsAdmin', 'entity', array(
					'class' => 'EasyVoteBundle:User', 
					'property' => 'euid', 
					'choices' => $adminArray,
					'empty_value' => 'Choose an option', 
					'required' => false,
					'multiple' => false
				)
			)			
		    ->add('save', 'submit', array(
					'label' => 'Save'
				)
			)			
            ->getForm();
		
        // This block has "what to do if form is being submitted"
        if ($request->getMethod() == 'POST') 
        {
            $form->handleRequest($request);
            if ($form->isValid()) 
            {			
				$data = $form->getData();

				// Adds the EUID as an admin
				if ($data['addEuidAsAdmin'] != null) 
				{						
					if (!empty($data['addEuidAsAdmin'])) 
					{
						// Find the user in the user repository
						$userToEdit = $userRepo->findOneByEuid($data['addEuidAsAdmin']->getEuid());
						if ($userToEdit) 
						{
							// If the user exists, then add the admin role
							$userToEdit->addRole($roleRepo->findOneByValue('ROLE_ADMIN'));
							$em->persist($userToEdit);
							$em->flush($userToEdit);							
						}
					}
				}
				
				$removeSelf = false;
				// Removes the EUID is as admin
				if ($data['removeEuidAsAdmin'] != null) 
				{					
					if (!empty($data['removeEuidAsAdmin'])) 
					{
						// Find the user in the user repository
						$userToEdit = $userRepo->findOneByEuid($data['removeEuidAsAdmin']->getEuid());
						if ($userToEdit) 
						{
							// If the user exists, then remove the admin role
							$userToEdit->removeRole($roleRepo->findOneByValue('ROLE_ADMIN'));	
							if ($userToEdit == $this->getUser()) {
								$removeSelf = true;
							}
								
							$em->persist($userToEdit);
							$em->flush($userToEdit);							
						}						
					}
				}											
				
				// Redirect back to the admin page, if you're still an admin
				if ($removeSelf == false) {
					return $this->redirect($this->generateUrl('admin_show'));
				}
				// Redirect to the election page if you remove yourself as an admin
				else {
					return $this->redirect($this->generateUrl('elections_show'));
				}
            }
        }				
		
        // This block has "show the form"
        return $this->render('EasyVoteBundle:Admin:show.html.twig', array('isAdmin' => $this->getUser()->isAdmin(), 'form_view' => $form->createView(), 'admin_list' => $adminArray, 'user_list' => $userArray));
    }
}
